import json
import logging as log
import urllib.request

try:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

except ImportError as e:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

try:
    from .info_config import cmdb_url
    from .info_config import platform_url
    from .info_config import cmdb_username
    from .info_config import cmdb_password
    from .info_config import platform_username
    from .info_config import platform_password
except Exception as e:
    from info_config import cmdb_url
    from info_config import platform_url
    from info_config import cmdb_username
    from info_config import cmdb_password
    from info_config import platform_username
    from info_config import platform_password


def message_format(body):
    # log.info(str(body))
    try:
        # message = bytes.decode(body)
        message = str(body)
        # message1 = json.loads(message)
        message_eval = eval(message)
        for key, value in message_eval.items():
            if isinstance(value, bytes):
                message_eval.update({key: str(value, encoding="utf-8")})
        return message_eval
    except Exception as e:
        log.exception(str(e))
        return


def get_token(platform="cmdb"):
    if platform == "cmdb":
        auth_url = "/auth/token"
        base_url = cmdb_url
        username = cmdb_username
        password = cmdb_password
    elif platform == "platform":
        auth_url = "/auth/token/user_login"
        base_url = platform_url
        username = platform_username
        password = platform_password
    else:
        return
    message = {
        'eauth': "pam",
        "username": username,
        "password": password
    }
    # auth_url = "/auth/token"
    request_url = "{base_url}{auth_url}".format(base_url=base_url,
                                                auth_url=auth_url)
    request = Request(request_url, urlencode(message).encode())
    body = urlopen(request).read().decode()
    token_info = message_format(body)
    token = token_info.get("token")
    log.debug(token)
    return "bearer " + token


def info_interactive_with_dbpt(suffix_url,
                               args_send,
                               platform="cmdb",
                               method="POST"):
    token_get = get_token(platform=platform)
    if token_get is None:
        return
    args_send_formated = json.dumps(args_send)
    if platform == "cmdb":
        base_url = cmdb_url
    elif platform == "platform":
        base_url = platform_url
    else:
        return
    request_url = "{}{}".format(base_url, suffix_url)
    req = urllib.request.Request(url=request_url,
                                 data=bytes(
                                     args_send_formated.encode("utf-8")),
                                 method=method)

    log.debug(request_url)
    req.add_header("Content-type", "application/json; charset=UTF-8")
    req.add_header("Authorization", token_get)
    with urllib.request.urlopen(req) as resp:
        response_data = json.loads(resp.read().decode("utf-8"))
        log.debug(response_data)
    return response_data


def get_proxysql_instance_info_by_mysql_instance_info(mysql_host, mysql_port):
    data = {
        "mysql_host": mysql_host,
        "mysql_port": mysql_port,
    }
    suffix_url = "/instance/base/get_proxysql_by_mysql_instance"
    return_value = info_interactive_with_dbpt(suffix_url=suffix_url, args_send=data)
    log.debug(return_value)
    proxysql_instance_list_info = return_value.get("data")
    if isinstance(proxysql_instance_list_info, list) and len(proxysql_instance_list_info) > 0:
        proxysql_host = proxysql_instance_list_info[0].get("private_ip")
        proxysql_port = proxysql_instance_list_info[0].get("port")
        return proxysql_host, proxysql_port
    else:
        return None, None


def get_proxysql_admin_password(proxysql_host, proxysql_port):
    data = {
        "proxysql_host": proxysql_host,
        "proxysql_admin_port": proxysql_port,
    }
    suffix_url = "/user_manage/mysql_user_manage/get_proxysql_admin_user_password"
    return_value = info_interactive_with_dbpt(suffix_url=suffix_url, args_send=data, method="GET")
    log.debug(return_value)
    admin_username = return_value.get("admin_username")
    proxysql_password = return_value.get("admin_password")
    return proxysql_password


def get_mysql_password(mysql_host, mysql_port, allow_host, user_name='repuser'):
    data = {
        "mysql_host": mysql_host,
        "mysql_port": mysql_port,
        "username": user_name,
        "allow_host": allow_host,
    }
    suffix_url = "/user_manage/mysql_user_manage/get_proxysql_admin_user_password"
    # return_value = info_interactive_with_dbpt(suffix_url=suffix_url, args_send=data, method="GET")
    return_value = info_interactive_with_dbpt(suffix_url=suffix_url,
                                              args_send=data,
                                              platform="cmdb",
                                              method="POST")
    log.debug(return_value)
    user_password = return_value.get("password")
    return user_password


def send_alert(alert_message, ding_receiver=1):
    # return
    suffix_url = "/alert_center/ding_alert/ding_alert"
    data = {"ding_receiver": ding_receiver, "msgtype": 'text', "text": alert_message}
    info_interactive_with_dbpt(suffix_url=suffix_url, args_send=data, platform="platform")


if __name__ == "__main__":
    proxysql_host, proxysql_port = get_proxysql_instance_info_by_mysql_instance_info("10.200.11.25", 8101)
    print(proxysql_host)
    print(proxysql_port)
